<template>
    <section class="form-container">
        <div class="form-content">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-button type="primary" size="mini" @click="showInsert({parentId:0})" icon="el-icon-plus">添加顶级角色</el-button>
                    <div class="custom-tree-container">
                        <el-tree
                            :data="dataSource"
                            node-key="id"
                            :highlight-current="true"
                            :expand-on-click-node="false"
                            :props="roleProps"
                            :default-expanded-keys="defaultExpandedKeys"
                            @node-click="getRoleAction"
                            @node-expand="nodeExpand"
                            @node-collapse="nodeCollapse"
                        >
                            <template #default="{ node, data }">
                                <div class="custom-tree-node">
                                    <span>{{ node.label }}</span>
                                    <span>
                                      <el-popconfirm
                                          v-if="data.children.length === 0"
                                          title="确定删除吗？"
                                          @onConfirm="handleDelete(data.id,node)"
                                      >
                                        <el-button slot="reference" size="mini" @click.stop="" style="margin-right:10px;">删除</el-button>
                                      </el-popconfirm>

                                      <el-button size="mini" @click.stop="showInsert(data)">添加</el-button>
                                      <el-button size="mini" @click.stop="showUpdate(data)">修改</el-button>
                                    </span>
                                </div>
                            </template>
                        </el-tree>
                    </div>
                </el-col>
                <el-col :span="12">
                    <el-tree
                        ref="treeRef"
                        :data="actionSource"
                        show-checkbox
                        node-key="permissionId"
                        :props="actionProps"
                    />


                </el-col>
            </el-row>

            <div style="display:flex;justify-content: center; margin-top:50px;">
                <div>
                    <el-button type="primary" size="mini" @click="saveRoleAction()">保存</el-button>
                </div>
            </div>

            <Update ref="updateRef" @refresh="getAllList()"/>
        </div>
    </section>
</template>
<script>
import {RoleApi} from '@/api/system/RoleApi'
import {RolePermissionApi} from '@/api/system/RolePermissionApi'
import {PermissionApi} from '@/api/system/PermissionApi'
import Update from './Update.vue'
import {Message} from 'element-ui'

export default {
    name: 'SystemRoleList',
    components: {Update},
    data() {
        return {
            dataSource: [],
            roleProps: {
                children: 'children',
                label: 'roleName'
            },
            actionSource: [],
            actionProps: {
                children: 'children',
                label: 'title'
            },
            activeRoleId: 0,
            defaultExpandedKeys: []
        }
    },
    created() {
        this.getAllList()
        this.getAction()
    },
    methods: {
        // 获取所有角色
        getAllList() {
            RoleApi.getAllList()
                .then((response) => {
                    this.dataSource = response
                })
        },
        // 获取所有权限
        getAction() {
            PermissionApi.getAllList()
                .then((response) => {
                    this.actionSource = response
                })
        },
        // 添加角色
        showInsert(data) {
            const newData = {
                'id': 0,
                'parentId': data.id
            }
            this.$refs['updateRef'].showUpdate(newData)
        },
        // 修改角色
        showUpdate(data) {
            this.$refs['updateRef'].showUpdate(data)
        },
        // 删除角色
        handleDelete(id, node) {
            RoleApi.delete(id)
                .then((response) => {
                    this.$refs['treeRef'].setCheckedKeys([])
                    node.remove()
                })
        },
        // 保存角色权限
        saveRoleAction() {
            const permissionIds = this.$refs['treeRef'].getCheckedKeys(false).concat(this.$refs['treeRef'].getHalfCheckedKeys(true))

            if (!this.activeRoleId) {
                Message({
                    message: '请选择角色',
                    type: 'warning'
                })

                return false
            }

            RolePermissionApi.insert({roleId: this.activeRoleId, permissionIds: permissionIds})
                .then(() => {
                })
        },

        // 获取角色权限
        getRoleAction(data) {
            const that = this
            that.activeRoleId = data.id

            RolePermissionApi.getIdArr(this.activeRoleId).then((response) => {
                // 只设置最小级别，解决父级半选问题
                const minActionArr = that.getMinAction(that.actionSource)

                const data = []
                response.forEach(function (actionId) {
                    if (minActionArr.includes(actionId)) {
                        data.push(actionId)
                    }
                })
                that.$refs['treeRef'].setCheckedKeys(data)
            })
        },

        // 获取最小级权限
        getMinAction(dataList) {
            let arr = []
            for (let i = 0; i < dataList.length; i++) {
                if (dataList[i]['children']) {
                    arr = arr.concat(this.getMinAction(dataList[i]['children']))
                } else {
                    arr.push(dataList[i].permissionId)
                }
            }
            return arr
        },
        nodeExpand(e) {
            this.defaultExpandedKeys.push(e.id)
        },
        nodeCollapse(e) {
            this.defaultExpandedKeys = this.defaultExpandedKeys.filter((x) => x !== e.id)
        }

    }
}

</script>

<style>
.custom-tree-container {
    margin-top: 30px;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}

.el-tree-node__content {
    height: 36px !important;
}
</style>
